<?php
/**
 * 截取UTF-8编码下字符串的函数
 *
 * @param   string      $str        被截取的字符串
 * @param   int         $length     截取的长度
 * @param   bool        $append     是否附加省略号
 *
 * @return  string
 */
function sub_str($str, $length = 0, $append = true)
{
    $str = trim($str);
    $strlength = strlen($str);

    if ($length == 0 || $length >= $strlength)
    {
        return $str;
    }
    elseif ($length < 0)
    {
        $length = $strlength + $length;
        if ($length < 0)
        {
            $length = $strlength;
        }
    }

    if (function_exists('mb_substr'))
    {
        $newstr = mb_substr($str, 0, $length, 'UTF-8');
    }
    elseif (function_exists('iconv_substr'))
    {
        $newstr = iconv_substr($str, 0, $length, 'UTF-8');
    }
    else
    {
        $newstr = trim_right(substr($str, 0, $length));
    }

    if ($append && $str != $newstr)
    {
        $newstr .= '...';
    }

    return $newstr;
}

/**
 * 去除字符串右侧可能出现的乱码
 *
 * @param   string      $str        字符串
 *
 * @return  string
 */
function trim_right($str)
{
    $length = strlen(preg_replace('/[\x00-\x7F]+/', '', $str)) % 3;

    if ($length > 0)
    {
        $str = substr($str, 0, 0 - $length);
    }

    return $str;
}

/**
 * 计算字符串的长度（汉字按照两个字符计算）
 *
 * @param   string      $str        字符串
 *
 * @return  int
 */
function str_len($str)
{
    $length = strlen(preg_replace('/[\x00-\x7F]/', '', $str));

    if ($length)
    {
        return strlen($str) - $length + intval($length / 3) * 2;
    }
    else
    {
        return strlen($str);
    }
}

/**
 * 获得用户操作系统的换行符
 *
 * @access  public
 * @return  string
 */
function get_crlf()
{
/* LF (Line Feed, 0x0A, \N) 和 CR(Carriage Return, 0x0D, \R) */
    if (stristr($_SERVER['HTTP_USER_AGENT'], 'Win'))
    {
        $the_crlf = '\r\n';
    }
    elseif (stristr($_SERVER['HTTP_USER_AGENT'], 'Mac'))
    {
        $the_crlf = '\r'; // for old MAC OS
    }
    else
    {
        $the_crlf = '\n';
    }

    return $the_crlf;
}

/**
 * 创建像这样的查询: "IN('a','b')";
 *
 * @access   public
 * @param    mix      $item_list      列表数组或字符串
 * @param    string   $field_name     字段名称
 * @author   Xuan Yan
 *
 * @return   void
 */
function db_create_in($item_list, $field_name = '')
{
    if (empty($item_list))
    {
        return $field_name . " IN ('') ";
    }
    else
    {
        if (!is_array($item_list))
        {
            $item_list = explode(',', $item_list);
        }
        $item_list = array_unique($item_list);
        $item_list_tmp = '';
        foreach ($item_list AS $item)
        {
            if ($item !== '')
            {
                $item_list_tmp .= $item_list_tmp ? ",'$item'" : "'$item'";
            }
        }
        if (empty($item_list_tmp))
        {
            return $field_name . " IN ('') ";
        }
        else
        {
            return $field_name . ' IN (' . $item_list_tmp . ') ';
        }
    }
}

/**
 * 获得用户的真实IP地址
 *
 * @access  public
 * @return  string
 */
function real_ip()
{
    static $realip = NULL;

    if ($realip !== NULL)
    {
        return $realip;
    }

    if (isset($_SERVER))
    {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);

            /* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */
            foreach ($arr AS $ip)
            {
                $ip = trim($ip);

                if ($ip != 'unknown')
                {
                    $realip = $ip;

                    break;
                }
            }
        }
        elseif (isset($_SERVER['HTTP_CLIENT_IP']))
        {
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        }
        else
        {
            if (isset($_SERVER['REMOTE_ADDR']))
            {
                $realip = $_SERVER['REMOTE_ADDR'];
            }
            else
            {
                $realip = '0.0.0.0';
            }
        }
    }
    else
    {
        if (getenv('HTTP_X_FORWARDED_FOR'))
        {
            $realip = getenv('HTTP_X_FORWARDED_FOR');
        }
        elseif (getenv('HTTP_CLIENT_IP'))
        {
            $realip = getenv('HTTP_CLIENT_IP');
        }
        else
        {
            $realip = getenv('REMOTE_ADDR');
        }
    }

    preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
    $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';

    return $realip;
}

/**
 * 验证输入的邮件地址是否合法
 *
 * @access  public
 * @param   string      $email      需要验证的邮件地址
 *
 * @return bool
 */
function is_email($user_email)
{
        $chars = "/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,6}\$/i";
        if (strpos($user_email, '@') !== false && strpos($user_email, '.') !== false)
     {
        if (preg_match($chars, $user_email))
        {
            return true;
        } else
        {
            return false;
        }
    } else
        {
            return false;
        }
}

/**
 * 检查是否为一个合法的时间格式
 *
 * @access  public
 * @param   string  $time
 * @return  void
 */
function is_time($time)
{
    $pattern = '/[\d]{4}-[\d]{1,2}-[\d]{1,2}\s[\d]{1,2}:[\d]{1,2}:[\d]{1,2}/';

    return preg_match($pattern, $time);
}

function add_friend($uid){
    if(!empty($uid)){
        $user_id=$_SESSION['user_id'];
        $sql="SELECT COUNT(*) FROM ".$GLOBALS['dtb']->table("friend")." WHERE `user_id`='$user_id' AND `friend_id`='$uid'";
        $count=$GLOBALS['db']->getOne($sql);
        $count=empty($count)?0:intval($count);
        if($count<=0){
           
            $sql="INSERT INTO  ".$GLOBALS['dtb']->table("friend")." ( `user_id` , `friend_id`,`addtime` )".
            " VALUES ('$user_id','$uid','".time()."') ";
            
            $GLOBALS['db']->query($sql);
            return true;
        }else{
            return false;
        }
    }else{
       return false; 
    }
}

function set_user_integral($user_id,$user_integral=0,$type=0){
    if($type==0){
        $sql="UPDATE ".$GLOBALS['dtb']->table("users")." SET user_integral=user_integral+'$user_integral' WHERE user_id ='".$user_id."'";
    }else{
        $sql="UPDATE ".$GLOBALS['dtb']->table("users")." SET user_integral=user_integral+'$user_integral' WHERE user_name ='".$user_id."'";
    }
    $GLOBALS['db']->query($sql);
}

function gourl($url){
    if(!empty($url)){
    header("Location:$url");die();
    }
}


/**
 * 邮件发送
 *
 * @param: $name[string]        接收人姓名
 * @param: $email[string]       接收人邮件地址
 * @param: $subject[string]     邮件标题
 * @param: $content[string]     邮件内容
 * @param: $type[int]           0 普通邮件， 1 HTML邮件
 * @param: $notification[bool]  true 要求回执， false 不用回执
 *
 * @return boolean
 */

function send_mail($name, $email, $subject, $content, $type = 0, $notification=false)
{
    /* 如果邮件编码不是utf8，创建字符集转换对象，转换编码 */
    if ($GLOBALS['_CFG']['mail_charset'] != 'UTF8')
    {
        $name      = iconv('UTF8', $GLOBALS['_CFG']['mail_charset'], $name);
        $subject   = iconv('UTF8', $GLOBALS['_CFG']['mail_charset'], $subject);
        $content   = iconv('UTF8', $GLOBALS['_CFG']['mail_charset'], $content);
        $GLOBALS['_CFG']['site_name'] = iconv('UTF8', $GLOBALS['_CFG']['mail_charset'], $GLOBALS['_CFG']['site_name']);
        $charset   = $GLOBALS['_CFG']['mail_charset'];
    }
    else
    {
        $charset = 'UTF-8';
    }

    /**
     * 使用mail函数发送邮件
     */
    if ($GLOBALS['_CFG']['mail_service'] == 0 && function_exists('mail'))
    {
        
        /* 邮件的头部信息 */
        $content_type = ($type == 0) ?
            'Content-Type: text/plain; charset=' . $charset : 'Content-Type: text/html; charset=' . $charset;


        $headers = array();
        $headers[] = 'From: "' . '=?' . $charset . '?B?' . base64_encode($GLOBALS['_CFG']['site_name']) . '?='.'" <' . $GLOBALS['_CFG']['smtp_mail'] . '>';
        $headers[] = $content_type . '; format=flowed';
        if ($notification)
        {
            $headers[] = 'Disposition-Notification-To: ' . '=?' . $charset . '?B?' . base64_encode($GLOBALS['_CFG']['site_name']) . '?='.'" <' . $GLOBALS['_CFG']['smtp_mail'] . '>';
        }

        $res = @mail($email, '=?' . $charset . '?B?' . base64_encode($subject) . '?=', $content, implode("\r\n", $headers));

        if (!$res)
        {
            

            return false;
        }
        else
        {
            return true;
        }
    }
    /**
     * 使用smtp服务发送邮件
     */
    else
    {
        /* 邮件的头部信息 */
        $content_type = ($type == 0) ?
            'Content-Type: text/plain; charset=' . $charset : 'Content-Type: text/html; charset=' . $charset;
        $content   =  base64_encode($content);

        $headers = array();
        $headers[] = 'Date: ' . gmdate('D, j M Y H:i:s') . ' +0000';
        $headers[] = 'To: "' . '=?' . $charset . '?B?' . base64_encode($name) . '?=' . '" <' . $email. '>';
        $headers[] = 'From: "' . '=?' . $charset . '?B?' . base64_encode($GLOBALS['_CFG']['site_name']) . '?='.'" <' . $GLOBALS['_CFG']['smtp_mail'] . '>';
        $headers[] = 'Subject: ' . '=?' . $charset . '?B?' . base64_encode($subject) . '?=';
        $headers[] = $content_type . '; format=flowed';
        $headers[] = 'Content-Transfer-Encoding: base64';
        $headers[] = 'Content-Disposition: inline';
        if ($notification)
        {
            $headers[] = 'Disposition-Notification-To: ' . '=?' . $charset . '?B?' . base64_encode($GLOBALS['_CFG']['site_name']) . '?='.'" <' . $GLOBALS['_CFG']['smtp_mail'] . '>';
        }

        /* 获得邮件服务器的参数设置 */
        $params['host'] = $GLOBALS['_CFG']['smtp_host'];
        $params['port'] = $GLOBALS['_CFG']['smtp_port'];
        $params['user'] = $GLOBALS['_CFG']['smtp_user'];
        $params['pass'] = $GLOBALS['_CFG']['smtp_pass'];

        if (empty($params['host']) || empty($params['port']))
        {
            // 如果没有设置主机和端口直接返回 false
            

            return false;
        }
        else
        {
            // 发送邮件
            if (!function_exists('fsockopen'))
            {
                //如果fsockopen被禁用，直接返回
                

                return false;
            }

            include_once(ROOT_PATH.'include/cls_smtp.php');
            static $smtp;

            $send_params['recipients'] = $email;
            $send_params['headers']    = $headers;
            $send_params['from']       = $GLOBALS['_CFG']['smtp_mail'];
            $send_params['body']       = $content;

            if (!isset($smtp))
            {
                $smtp = new smtp($params);
            }

            if ($smtp->connect() && $smtp->send($send_params))
            {
                return true;
            }
            else
            {
                $err_msg = $smtp->error_msg();
                

                return false;
            }
        }
    }
}

function read_dir($dir,$start=0,$end=29) {     //dir为指定的目录参数
    $handle=opendir($dir);
    $i=0;
    while($file=readdir($handle)) {
    if (($file!=".")and($file!="..")and($file!="Thumbs.db")) {
    //.和..是当前目录和上级目录的硬链接，这里不需要
    if($i>=$start&&$i<=$end){
    $list[$i]=iconv("GB2312","UTF-8",$file);
    }
    $i=$i+1;
    }
    }
    closedir($handle); 
    return $list;
}
function read_dir_count($dir) {     //dir为指定的目录参数
    $handle=opendir($dir);$list=0;
    while($file=readdir($handle)){
        $list+=1;
    }
    return $list-2;
}

function add_email($email,$flag=0){
    global $user_id;
    if(!is_email($email)){return false;}
    $sql="SELECT count(*) FROM ".$GLOBALS['dtb']->table("emaillist")." WHERE email='$email'";
    $temp=$GLOBALS['db']->getOne($sql);
    if(empty($temp)||$temp<=0){
        $sql="INSERT INTO ".$GLOBALS['dtb']->table("emaillist")." (email,user_id) ".
            " VALUES('$email','$user_id')";
         $GLOBALS['db']->query($sql);
         if($flag==1){update_email($email);}
    }
}

function update_email($email){
    $sql="UPDATE ".$GLOBALS['dtb']->table("emaillist")." SET send_ok='1' WHERE email='$email' AND send_ok!='1' ";
    $GLOBALS['db']->query($sql);
}
function get_email($emailc)
{
        preg_match_all('/\\b[A-Z0-9._%-]+@[A-Z0-9._%-]+\\.[A-Z]{2,4}\\b/i', $emailc, $emaillist, PREG_PATTERN_ORDER);
        if (!empty($emaillist))
        {
            return $emaillist;
        } else
        {
            return false;
        }
}
?>